<template>
  <div>

   <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-page-header @back="$router.back()" :content="formParams.courseName">
        </el-page-header>
        <!-- <span >{{params.id ? '编辑' : '新增'}}</span> -->
      </div>
      <el-tree
        draggable
        @node-drop="handleSort"
        :allow-drop="handleAllowDrop"
        :data="data"
        :props="defaultProps"
      >
        <div class="inner" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>
          <span>
            <el-button plain size="small" @click.stop="handleAddOrEdit(data,'编辑')">编辑</el-button>
            <el-button size="small" @click.stop="handleAddOrEdit(data,'添加课程')" v-if="data.description" type="primary"
              >添加课程</el-button
            >
            <el-button @click.stop="handleUpload(data)" size="small" @click="$router.push({name:'coursesVideo',params:{ id },query:{
                sectionId: node.parent.id,
                lessonId: data.id

            }})" v-else type="success">上传视频</el-button>
            <el-dropdown :hide-on-click="false"  style="margin-left: 10px">
              <el-button @click.stop size="small" >
                {{ data.status === 0 ?'已隐藏' :data.status === 1 ?
                  '待更新' : '已发布' }}
                <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :disabled="data.status === 0" @click.native="handleStatus(0 ,'隐藏', data)">隐藏</el-dropdown-item>
                <el-dropdown-item :disabled="data.status === 1" @click.native="handleStatus(1 ,'更新', data)">更新</el-dropdown-item>
                <el-dropdown-item :disabled="data.status === 2" @click.native="handleStatus(2 ,'发布', data)">发布</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </span>
        </div>
      </el-tree>
   </el-card>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="50%"
       >
       <dh-form
        v-if="title === '编辑'"
        label-width="100px"
        label-position="left"
        :formConfig="formEditConfig"
        :formParams="formParams"
        ref="dhEditForm"
      />
       <dh-form
        v-else
        label-width="100px"
        label-position="left"
        :formConfig="formAddConfig"
        :formParams="formParams"
        ref="dhAddForm"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEdit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import {
  getSectionAndLesson,
  saveOrUpdateSection,
  saveOrUpdateLesson,
  getCourseById
} from '@/services/course'
import DhForm from '@/components/dh-components/dh-form/index.vue'
export default Vue.extend({
  name: 'coursesSections',
  components: {
    DhForm
  },
  props: {
    id: {
      type: [String, Number]
    }
  },
  data () {
    return {
      title: '编辑',
      data: [],

      dialogVisible: false,
      defaultProps: {
        children: 'lessonDTOS',
        label: (data: any) => data.description || data.theme
      },

      formParams: {
        courseName: ''
      },
      formEditConfig: [
        {
          name: 'courseName',
          label: '课程名称',
          disabled: true
        },
        {
          name: 'sectionName',
          label: '章节名称'
        },
        {
          name: 'description',
          label: '章节描述'
        },
        {
          name: 'orderNum',
          label: '章节排序',
          append: '数字控制排序，数字越大越靠后',
          type: 'number'
        }
      ],
      formAddConfig: [
        {
          name: 'courseName',
          label: '课程名称',
          disabled: true
        },
        {
          name: 'sectionName',
          label: '章节名称',
          disabled: true
        },
        {
          name: 'theme',
          label: '课时名称'
        },
        {
          name: 'duration',
          label: '时长',
          append: '分钟',
          type: 'number'
        },
        {
          name: 'isFree',
          label: '是否开放试听',
          htmlType: 'switch'
        },
        {
          name: 'orderNum',
          label: '课时排序',
          append: '数字控制排序，数字越大越靠后',
          type: 'number'
        }
      ]
    }
  },
  created () {
    this.queryTreeList()
  },
  methods: {
    // 获取树
    async queryTreeList () {
      const [{ data }, {
        data: {
          courseName
        }
      }] = await Promise.all([getSectionAndLesson({ courseId: this.id }), getCourseById({ courseId: this.id })])
      this.data = data
      console.log(courseName, 'courseNamecourseNamecourseName')
      this.formParams.courseName = courseName
    },
    // 排序
    async handleSort (
      draggingNode: any,
      dropNode: any,
      type: string,
      event: any
    ) {
      await Promise.all(
        dropNode.parent.childNodes.map((item: any, index: any) => {
          if (item.data.description) {
            // 阶段
            return saveOrUpdateSection({
              id: item.data.id,
              orderNum: index + 1
            })
          } else {
            return saveOrUpdateLesson({
              id: item.data.id,
              orderNum: index + 1
            })
          }
        })
      )
      this.$message.success('排序成功')
    },
    // 拖拽
    handleAllowDrop (draggingNode: any, dropNode: any, type: string) {
      // console.log(draggingNode, dropNode, type)
      return (
        draggingNode.data.sectionId === dropNode.data.sectionId &&
        type !== 'inner'
      )
    },
    // 更新状态
    handleStatus (status: number, title: any, data: any) {
      this.$confirm(`确定${title}吗, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.$set(data, 'status', status)
        if (data.description) {
          // 阶段
          await saveOrUpdateSection({
            ...data,
            status
          })
        } else {
          await saveOrUpdateLesson({
            ...data,
            status
          })
        }
        this.$message({
          type: 'success',
          message: `${title}成功!`
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: `已取消${title}`
        })
      })
    },
    // 编辑
    handleAddOrEdit (data: any, title: string) {
      this.title = title
      this.dialogVisible = true
      this.formParams = { ...this.formParams, ...data }
    },
    async submitEdit () {
      const formParams: any = this.formParams
      if ((formParams).description && this.title === '编辑') {
        // 阶段
        await saveOrUpdateSection(formParams)
      } else {
        await saveOrUpdateLesson({ ...formParams, sectionId: formParams.sectionId || formParams.id })
      }
      this.$message.success('更新成功')
      this.dialogVisible = false
      this.queryTreeList()
    },
    // 上传
    handleUpload (data: any) {
      console.log(data)
    }
  }
})
</script>
<style lang='scss' scoped>
::v-deep .el-tree-node__content {
  height: auto;
  .inner {
    display: flex;
    flex: 1 0 0;
    justify-content: space-between;
    align-items: center;
    box-sizing: border-box;
    padding: 9px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  }
}
</style>
